package ks.client.gui.admin.user.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTable;
import org.w3c.dom.Document;
import ks.client.UserContext;
import ks.client.gui.ErrorMessageGUI;
import ks.client.ipc.Client;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;

/**
 * Sends a command to kick users off the system.
 * 
 * @author Jennifer Hunt
 *
 */
public class KickUsersClickController implements ActionListener{
	
	Lobby lobby;
	JTable table;
	
	/**
	 * Constructor for KickUsersClickController
	 * @param lobby
	 */
	public KickUsersClickController(Lobby lobby, JTable table) {
		this.lobby = lobby;
		this.table = table;
	}
	
	/**
	 * 
	 * When the "Kick Users" button is pressed, a command is sent to the server
	 * to kick the users defined in the table.
	 *  
	 */
	public void actionPerformed(ActionEvent e){
		if(table.getRowCount()==0){
			JFrame pma = new ErrorMessageGUI("Please add a user to the table in order to delete.");
			pma.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			pma.setTitle("Error");
			pma.setVisible(true);
		}
		else{
			int index = 0;
		
			String s = "<admin-command version= \"1.0\" id=\"589a39591271844e3fbe32bbb9281ad9\">" +
			"<user-kick>"; 
			String u;
		
			while(index < table.getRowCount()){
				u = "<playername name=\"" + table.getValueAt(index, 0) + "\"/>";
				s = s + u;
				index++;
			}
	
			u = "</user-kick>" + "</admin-command>";
			s = s + u;
		
			Document d = Message.construct(s);
			Message m = new Message(d);

			//send to server
			UserContext uc = lobby.getUserContext();
			Client c = uc.getClient();
			c.sendToServer(m);
		}
	}
}
